package com.auto.api.core.type.json.yapi;

import com.auto.api.core.constants.MappingConstants;
import com.auto.api.common.utils.JsonMapper;
import com.auto.api.core.type.TypeFactory;
import com.auto.api.core.type.defaultvalue.ValueTypeHandler;
import com.auto.api.core.util.BeanUtil;
import java.util.Map;
import org.springframework.core.ResolvableType;

/**
 * @program:
 * @description: CollectionApiResultJsonTypeHandler类型处理器
 * @author: liangshf
 * @create: 2020-09-24
 */
public class CollectionApiResultJsonTypeHandler extends AbstractApiResultJsonTypeHandler {

    @Override
    public boolean canCovert(ResolvableType resolvableType) {
        return resolvableType.isArray();
    }

    @Override
    public String getResultJson(ResolvableType resolvableType, Map root) {
        Map list = BeanUtil.getProperties("array", MappingConstants.EMPTY_STRING);
        Map itemsProperties = BeanUtil.getProperties(MappingConstants.EMPTY_STRING, MappingConstants.EMPTY_STRING);
        Map items;
        if (resolvableType.hasGenerics()) {
            ResolvableType genType = resolvableType.getGenerics()[0];
            Class rowClass = genType.getRawClass() == null ? String.class : genType.getRawClass();
            ValueTypeHandler typeHandler = TypeFactory.getTypeHandler(rowClass.getSimpleName());
            if (typeHandler != null) {
                items = BeanUtil.getProperties(rowClass.getSimpleName(), MappingConstants.EMPTY_STRING);
                list.put("items", items);
                root.putAll(list);
                return JsonMapper.toJson(root);
            }
            items = BeanUtil.getProperties("object", "结果对象");
            Map<String, Object> map = BeanUtil.getResultApiMap(genType);
            itemsProperties.putAll(map);
        } else {
            items = BeanUtil.getProperties(String.class.getSimpleName(), MappingConstants.EMPTY_STRING);
        }
        items.put("properties", itemsProperties);
        list.put("items", items);
        root.putAll(list);
        return JsonMapper.toJson(root);
    }
}